package org.yray.sip.visit;

import org.yray.sip.base.SipMsg;
import org.yray.sip.constant.SessionStatusEnum;
import org.yray.sip.constant.SipCodeEnum;
import org.yray.sip.factory.SipSessionFactory;
import org.yray.sip.factory.StopWatchFactory;
import org.yray.sip.rtp.receive.AbstractBeanHolder;
import org.yray.sip.rtp.sender.ISipSessionCache;
import org.yray.sip.server.SipServerContext;
import org.yray.sip.server.SipSession;
import org.yray.sip.utils.IcspBeanHolder;

import java.net.InetSocketAddress;


public class Sip200Visitor extends AbstractBeanHolder implements ISipVisitor{

    @Override
    public void doALeg(SipMsg sipMsg, SipServerContext ssc) {
        log(sipMsg.getCallId(),"Sip200Visitor,doALeg");
        SipSession sipSession= IcspBeanHolder.getBean(ISipSessionCache.class).get(sipMsg.getCallId());
        //改变识别类型
        sipSession.getStatus().set(SessionStatusEnum.ANSWER);
        getStopWatchFactory().periodStart(sipSession, StopWatchFactory.TASK_200_A);
        getEventFactory().sipEvent(sipMsg.getCallId(), SipCodeEnum.SIP_OK_A);
    }

    @Override
    public void doBLeg(SipMsg sipMsg, SipServerContext ssc) {
        log(sipMsg.getCallId(),"Sip200Visitor,doBLeg");
        SipSession sipSession=IcspBeanHolder.getBean(ISipSessionCache.class).get(sipMsg.getCallId());
        if(sipSession==null)
        {
            log(sipMsg.getCallId(),"sipSession is null ,maybe phone has close");
            return;
        }
        SipSession sourceSipSession=IcspBeanHolder.getBean(ISipSessionCache.class).get(sipSession.getSourceId());
        if(sourceSipSession==null)
        {
            log(sipMsg.getCallId(),"sourceSipSession is null ,maybe phone has close");
            return;
        }
        //这里应答了，把双方的媒体流端口交换一下
        IcspBeanHolder.getBean(SipSessionFactory.class).resolvRtp(sipSession,sipMsg.getSdpList());
        sipSession.getStatus().set(SessionStatusEnum.TO_MAN_SUCC);
        IcspBeanHolder.getBean(ISipSessionCache.class).addRtcpIp(sipSession);
        getRtcpSender().sendRR(ssc,sipSession.getCallId());
        IcspBeanHolder.getBean(ISipSessionCache.class).putRecvPort(sipSession.getSideRtcpIp() + sipSession.getSideRtpPort(), sipSession.getCallId());
        //更新下缓存里在信息
        sipSession.setSipMap(sipMsg.getSipMap());
        sipSession.setOtherRtpSender(sourceSipSession.mySideRtpSender());
        sourceSipSession.setToManId(sipSession.getCallId());
        sourceSipSession.getStatus().set(SessionStatusEnum.TO_MAN_SUCC);
        sourceSipSession.setOtherRtpSender(new InetSocketAddress(sipSession.getSideRtcpIp(),sipSession.getSideRtpPort()));
        getStopWatchFactory().periodStart(sipSession, StopWatchFactory.TASK_200_B);
        getEventFactory().sipEvent(sipMsg.getCallId(), SipCodeEnum.SIP_OK_B);
    }
}
